package com.banmao.greedysnake.gamepanel.service;

import com.banmao.greedysnake.gamepanel.controller.GamePanelCcontroller;
import com.banmao.greedysnake.util.SpringContextUtil;
import com.banmao.greedysnake.vo.Constants;
import com.banmao.greedysnake.vo.Food;
import com.banmao.greedysnake.vo.Snake;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

// 绘制工厂
@Slf4j
public class Painter {

    private static GamePanelCcontroller gamePanelCcontroller;

     static {
        gamePanelCcontroller = (GamePanelCcontroller) SpringContextUtil.getBean(GamePanelCcontroller.class);
    }

    public static void draw(GraphicsContext gc, Snake snake) {
        // 清空画布
        gc.clearRect(0, 0, Constants.CANCAS_WIDTH, Constants.CANCAS_HEIGHT);

        // 获取snake的bodies
        List<Snake.Body> bodies = snake.getBodies();

        // 绘制food
        Food food = snake.getFood();
        log.debug("绘制food 坐标: (x: {}, y: {})", food.getFoodX(), food.getFoodY());
        draw(gc, food.getFoodX(), food.getFoodY(), food.getFoodSize(), food.getFoodColor());

        StringBuilder sb = new StringBuilder("snake移动 各body坐标: ");
        /*int i = 1;
        for (Snake.Body body : bodies) {
            draw(gc, body.getX(), body.getY(), body.getSize(), body.getColor());
            sb.append("body").append(i++).append("(x: ").append(body.getX())
                    .append(", y: ").append(body.getY()).append("), ");
        }*/
        // 逆序绘制snake，让head永远呈现在最上面
        for (int j = bodies.size() - 1; j >= 0; j--) {
            Snake.Body body = bodies.get(j);
            if(j == 0) {
                draw(gc, body.getX(), body.getY(), body.getSize(), body.getColor());
            } else {
                gc.setFill(body.getColor());
                gc.fillRoundRect(body.getX(), body.getY(), body.getSize(), body.getSize(), 10, 10);
            }
            sb.append("body").append(j).append("(x: ").append(body.getX())
                    .append(", y: ").append(body.getY()).append("), ");
        }
        log.debug(sb.substring(0, sb.length() - 1));

        if(gamePanelCcontroller.getIsFail()) {
            // 游戏失败，打出字体
            log.info("打出结束提示");
            gc.setFill(Color.ROSYBROWN);
            Font font = Font.loadFont(Painter.class.getResourceAsStream("/fonts/whiteStyle.ttf"), 65);
            gc.setFont(font);
            //gc.setFont(new Font(65));
            gc.fillText("游戏结束！\n最终得分：" + snake.getScore(), Constants.CANCAS_WIDTH / 3 - 60, Constants.CANCAS_HEIGHT / 2 - 60, 50000);
            //gc.strokeText("游戏失败！", 100, 100, 50);
        }

    }

    private static void draw(GraphicsContext gc, Double x, Double y, Double size, Color color) {
        gc.setFill(color);
        gc.fillOval(x, y, size, size);
    }

}
